from cStringIO import StringIO
import os
import radix

path = os.path.abspath(os.path.dirname(__file__))
ISPs = ['UNI(CNC)', 'CHN', 'CTT', 'CMN', 'CER']
rad = radix.Radix()
for i in ISPs:
	filename = path + '/' + i
	try:
        	doc_string = open(filename).read()
        except:
		update()
	doc = StringIO(doc_string)
        for line in doc:
        	prefix = line.strip()
        	node = rad.add(prefix)
        	node.data.update({'isp':i})

def update():
	from urllib import urlopen
	import re

	re_c = re.compile(r'\d+\.\d+\.\d+\.\d+\/\d+')
	re_p = re.compile(r'[\d+\.]*\d+\/\d+')
	urls = [
		'http://www.lbase.net/Download/IPInfo-CN-UNICOM(CNC).txt',
		'http://www.lbase.net/Download/IPInfo-CN-ChinaTelcom.txt',
		'http://www.lbase.net/Download/IPInfo-CN-CTT.txt',
		'http://www.lbase.net/Download/IPInfo-CN-ChinaMobile.txt'
	]
	files = ['UNI(CNC)', 'CHN', 'CTT', 'CMN']
	for i in range(len(urls)):
		o = file(path+'/'+files[i], 'w')
		s = urlopen(urls[i]).read()
		f = StringIO(s)
		for l in f:
			r = re_c.search(l)
			if r == None:
				continue
			print >> o, r.group()
		o.close()
			
	o = file(path+'/'+'CER', 'w')	
	cer_url = 'http://www.nic.edu.cn/RS/ipstat/'
	s = urlopen(cer_url).read()
	f = StringIO(s)
	for l in f:
		ar = re_p.findall(l)
		for i in ar:
			pre, mask = i.split('/')
			for j in range(3-pre.count('.')):
				pre += '.0'
			print >> o, (pre+'/'+mask)		
	o.close()

def ip2isp(ip):
	node = rad.search_best(ip)
        if node == None:
                return None
        return node.data['isp']
